package business;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.ArrayList;
import java.util.ListIterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import orm.AORef;
import orm.IndividualClass;
import orm.IndividualTeachingPlan;
import orm.Teacher;
import orm.TeachingPlanBaseInfo;
import orm.Users;
import orm.CollectivityClass;

import dao.AORefDAO;
import dao.IndividualTeachingPlanDAO;
import dao.TeacherDAO;
import dao.CollectivityClassDAO;
import dao.TeachingPlanBaseInfoDAO;
import dao.UserDAO;
import util.Utility;
import util.DBHelper;

public class TeacherServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public TeacherServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int PageSize = Utility.PageSize;
		String strFunc = request.getParameter("func");
		
		if (strFunc == null) {
			return;
		} else if (strFunc.equals("load")) {
			request.setAttribute("degree", Utility.CONSTANT_DEGREE);
			request.setAttribute("assignment", Utility.CONSTANT_ASSIGNMENT);
			request.setAttribute("liability", Utility.CONSTANT_LIABILITY);
			
			request.getRequestDispatcher("../" + Utility.JSP_TeacherAdd).forward(request, response);
		} else if (strFunc.endsWith("save")) {
			String teacherID = request.getParameter("TeacherID").toString();
			TeacherDAO teacherDAO = new TeacherDAO();
			try {
				if (teacherDAO.doesExist(teacherID)) {
					request.setAttribute("flag", "flag");
					request.getRequestDispatcher("../" + Utility.JSP_TeacherAdd).forward(request, response);
					return;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			String userName = request.getParameter("UserName").toString();
			UserDAO userDAO = new UserDAO();
			try {
				if (userDAO.doesUserExist(userName)) {
					request.setAttribute("flagUserName", "flagUserName");
					request.getRequestDispatcher("../" + Utility.JSP_TeacherAdd).forward(request, response);
					return;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			Teacher teacher = new Teacher();
			Users user = new Users();

			pickupFormData(teacher, user, request);
//			teacher.setTeacherID(teacherID);
//			teacher.setUserName("scott");
			insertData(teacher, user);
					
			
			
			try {
				request.setAttribute("pageNo", 1);
				ArrayList<Teacher> al = teacherDAO.getAllTeachers();
				if (al.size() % PageSize == 0) {
					request.setAttribute("totalPage",al.size()/PageSize);
				} else {
					request.setAttribute("totalPage",(al.size()/PageSize) + 1);
				}
				
				al = new ArrayList<Teacher>();
				ListIterator<Teacher> it = teacherDAO.getAllTeachers().listIterator();
				int ii = 0;
				while (it.hasNext()) {
					Teacher t = it.next();
					Teacher t1 = new Teacher();
					t1.setTeacherID(t.getTeacherID());
					t1.setTeacherName(t.getTeacherName());
					t1.setSex(t.getSex());
					t1.setPosition(t.getPosition());
					t1.setAssignment(t.getAssignment()-1);
					t1.setLiability(t.getLiability()-1);
					
					al.add(t1);
					ii++;
					if(ii > (PageSize-1) ) {
						break;
					}
					
				}
				
				request.setAttribute("teacherList", al);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_TeacherInfo).forward(request, response);

		}else if (strFunc.equals("edit")) {
			Teacher teacher = new Teacher();
			Users user = new Users();
			CollectivityClass collectivityClass = new CollectivityClass();
			IndividualClass individualClass = new IndividualClass();
			
			String teacherID = request.getParameter("teacherID");	
			pickupFormData(teacher, user, request);
			int userID = Integer.parseInt(request.getParameter("userID"));
			teacher.setUserID(userID);
			updateData(teacher, user, teacherID);
			updateCollectivityClass(teacher, collectivityClass, teacherID);
			updateIndividualClass(teacher, individualClass, teacherID);
			TeacherDAO teacherDAO = new TeacherDAO();
//			try {
//				request.setAttribute("teacherList", teacherDAO.getAllTeachers());
//			} catch (SQLException e) {
//				
//			}
//			request.getRequestDispatcher("../" + Utility.JSP_TeacherInfo).forward(request, response);
			
			try {
				request.setAttribute("pageNo", 1);
				ArrayList<Teacher> al = teacherDAO.getAllTeachers();
				if (al.size() % PageSize == 0) {
					request.setAttribute("totalPage",al.size()/PageSize);
				} else {
					request.setAttribute("totalPage",(al.size()/PageSize) + 1);
				}
				
				al = new ArrayList<Teacher>();
				ListIterator<Teacher> it = teacherDAO.getAllTeachers().listIterator();
				int ii = 0;
				while (it.hasNext()) {
					Teacher t = it.next();
					Teacher t1 = new Teacher();
					t1.setTeacherID(t.getTeacherID());
					t1.setTeacherName(t.getTeacherName());
					t1.setSex(t.getSex());
					t1.setPosition(t.getPosition());
					t1.setAssignment(t.getAssignment()-1);
					t1.setLiability(t.getLiability()-1);
					
					al.add(t1);
					ii++;
					if(ii > (PageSize-1) ) {
						break;
					}
					
				}
				
				request.setAttribute("teacherList", al);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_TeacherInfo).forward(request, response);
		} 
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	public void pickupFormData(Teacher teacher, Users user, HttpServletRequest request) {		
		user.setRoleID(1);
		user.setUserName(request.getParameter("UserName"));
		user.setPwd(request.getParameter("Pwd"));
		
		String teacherID = request.getParameter("teacherID");	
//		teacher.setTeacherID(teacherID);
//		int userID = Integer.parseInt(request.getParameter("userID"));
//		teacher.setUserID(userID);
		teacher.setTeacherName(request.getParameter("TeacherName"));
//		teacher.setTeacherID(request.getParameter("TeacherID"));
		teacher.setSex(Integer.parseInt(request.getParameter("Sex")));
		
		String strDateTmp = request.getParameter("txtBirthdayYear");
		teacher.setBirthday(strDateTmp);
		
//		request.getSession().getAttribute("UserName").toString();
		teacher.setWorkingYears(request.getParameter("WorkingYears"));
		teacher.setDegree(Integer.parseInt(request.getParameter("Degree")));
		teacher.setPosition(request.getParameter("Position"));
		teacher.setDirection(request.getParameter("Direction"));
		teacher.setSpeciality(request.getParameter("Speciality"));
		teacher.setTeachingExperience(request.getParameter("TeachingExperience"));
		teacher.setGlory(request.getParameter("Glory"));
		teacher.setAssignment(Integer.parseInt(request.getParameter("Assignment")));
		teacher.setLiability(Integer.parseInt(request.getParameter("Liability")));
	}
	
	public void updateData(Teacher teacher, Users user, String teacherID) {
		Connection conn = DBHelper.getConnection();
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			conn.setAutoCommit(false);
			
			TeacherDAO teacherDAO = new TeacherDAO();
			UserDAO userDAO = new UserDAO();
//			teacher.setTeacherID(teacherID);
			teacherDAO.updateTeacher(stmt, user, teacher);
			
			
			conn.commit();
			
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException ee) {
				
			}
		}
	}
	public void updateCollectivityClass(Teacher teacher, CollectivityClass collectivityClass, String teacherID) {
		Connection conn = DBHelper.getConnection();
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			conn.setAutoCommit(false);
			
			TeacherDAO teacherDAO = new TeacherDAO();
//			teacher.setTeacherID(teacherID);
			teacherDAO.updateCollectivityClass(stmt, collectivityClass, teacher);
			
			
			conn.commit();
			
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException ee) {
				
			}
		}
	}
	public void updateIndividualClass(Teacher teacher, IndividualClass individualClass, String teacherID) {
		Connection conn = DBHelper.getConnection();
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			conn.setAutoCommit(false);
			
			TeacherDAO teacherDAO = new TeacherDAO();
//			teacher.setTeacherID(teacherID);
			teacherDAO.updateIndividualClass(stmt, individualClass, teacher);
			
			
			conn.commit();
			
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException ee) {
				
			}
		}
	}

	public void insertData(Teacher teacher, Users user) {
		try {
			TeacherDAO teacherDAO = new TeacherDAO();
			UserDAO userDAO = new UserDAO();
			teacherDAO.insertTeacher(teacher, user);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
